#!/usr/bin/python
# -*- coding: utf-8 -*-

__all__ = [u'install_translator', u'MO_FILE_DIR', u'tr_']

global tr_

import os
import sys
import gettext

tr_ = gettext.NullTranslations().ugettext
__builtins__['tr_'] = tr_

from _pylot.data.regexpr import match, co_i18n_locale
from _pylot.defaultconf import hardbook

TRANSLATORS = {}
__CURRENT_LOCALE = None

try :
  __file__
except NameError :
  co = sys._getframe(0).f_code
  __file__ = co.co_filename

MO_FILE_DIR = hardbook(u'i18n_gettext')
NAME = 'pylot'

if MO_FILE_DIR.exists() :
  for path in MO_FILE_DIR.listdir() :
    if os.path.isdir(path) and match(co_i18n_locale, (os.path.basename(path))) :
      locale = os.path.basename(path)
      TRANSLATORS[locale] = gettext.translation(NAME, MO_FILE_DIR,
        languages=[locale], fallback=True)

from _pylot.core.system import LANG

def install_translator(locale):
  global __CURRENT_LOCALE, tr_
  if locale == __CURRENT_LOCALE :
    return
  __CURRENT_LOCALE = locale
  try :
    tr = TRANSLATORS[locale]
  except KeyError :
    tr = gettext.NullTranslations()
  tr.install(unicode=True)
  tr_ = _
  __builtins__['tr_'] = _

